/*
 * Created by Wildish on 2016-10-31
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hfdemo.handler;

import com.wildish.hfdemo.utils.Global;
import com.wildish.hybridframework.core.HybridGlobal;
import com.wildish.hybridframework.jsbinding.proxy.DataHandler;
import com.wildish.hybridframework.utils.http.HttpHelper;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.HashMap;

import static com.wildish.hybridframework.utils.HttpBaseHelper.CONTENT_TYPE;
import static com.wildish.hybridframework.utils.HttpBaseHelper.CONTENT_TYPE_PLAIN;

public class CommonRequestHandler implements DataHandler {

    @Override
    public String getData(JSONObject parameter) {
        String result = "";
        try{
            JSONObject urlObj = parameter.optJSONObject("url");
            String remoteUrl = urlObj.optString("remote", "");
            if(StringUtils.isNotBlank(remoteUrl)) {
                JSONObject params = removeInnerParams(parameter);
                HashMap<String, String> header = new HashMap<>();
                header.put(CONTENT_TYPE, CONTENT_TYPE_PLAIN);
                if(Global.DEBUG) {
                    result = HttpHelper.get(Global.DEBUG_SERVER_URL + remoteUrl, params, header);
                } else {
                    result = HttpHelper.get(Global.SERVER_URL + remoteUrl, params, header);
                }
            } else {
                result = DataHandler.COMMON_FAIL_RESP;
            }
        } catch (Exception e) {
            HybridGlobal.logger.log(e);
            result = DataHandler.COMMON_FAIL_RESP;
        }
        return result;
    }

    private JSONObject removeInnerParams(JSONObject params) {
        params.remove("_local");
        params.remove("d");
        params.remove("method");
        params.remove("url");
        return params;
    }
}
